package com.shop.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.shop.constant.UserConstant;
import com.shop.domain.Category;
import com.shop.domain.Goods;
import com.shop.domain.MessageCenter;
import com.shop.domain.User;
import com.shop.enumeration.MessageStatusEnum;
import com.shop.service.CategoryService;
import com.shop.service.GoodsService;
import com.shop.service.MessageCenterService;
import com.shop.service.UserService;
import com.shop.util.MD5;
import com.shop.util.VerifyCode;
import com.shop.util.page.PageList;

/**
 * 
 * @author wenjuanhenxing
 * @version V1.0 UserController.java 2016-2-12 下午8:27:11
 */
@Controller("userController")
@RequestMapping("/user")
public class UserController {
	@Resource(name = "userServiceImpl")
	private UserService userService;

	@Resource(name = "goodsServiceImpl")
	private GoodsService goodsService;

	@Resource(name = "messageCenterServiceImpl")
	private MessageCenterService messageCenterService;

	@Resource(name = "categoryServiceImpl")
	private CategoryService categoryService;

	@RequestMapping("/add")
	@ResponseBody
	public Map<String, String> add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		String msg = new String(readRequest(request));
		JSONObject json = JSONObject.fromObject(msg);
		String username = json.getString("name");
		String password = json.getString("pwd");
		password = MD5.GetMD5Code(password);
		String email = json.getString("email");
		String phone = json.getString("phone");
		String address = json.getString("address");

		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		user.setPhone(phone);
		user.setAddress(address);

		Map<String, String> map = new HashMap<String, String>();
		String scode = json.getString("verifycode");
		String code = (String) request.getSession().getAttribute("randcode");
		if (!code.equalsIgnoreCase(scode)) { // 验证码错误
			map.put("result", "codeError");
			return map;
		}
		if (userService.usernameExists(username)) {
			map.put("result", "usernameExists");
			System.out.println("usernameExists");
		} else if (userService.emailExists(email)) {
			map.put("result", "emailExists");
			System.out.println("emailExists");
		} else {
			map.put("result", "correct");
			userService.add(user);
			request.getSession().setAttribute("user", user);
			System.out.println("addUserSucc");
		}
		return map;
	}

	@RequestMapping("/test")
	public void testEncoding(HttpServletRequest request)
			throws UnsupportedEncodingException {
		System.out.println(request.getParameter("realName"));
		String s = request.getParameter("realName");
		System.out.println("test 姓名" + s);
	}

	@RequestMapping("/verifycode")
	public void safedCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		VerifyCode.getVerifyCode(request, response);
	}

	// 提交用户实名认证
	@RequestMapping("/certify")
	public String submitCertify(
			@RequestParam("certification") MultipartFile file,
			HttpServletRequest request) throws UnsupportedEncodingException {
		// request.setCharacterEncoding("utf-8");
		if (file.isEmpty()) {
			System.out.println("未上传");
			return null;
		}
		User user = (User) request.getSession().getAttribute("currentUser");
		if (user == null) {
			// 临时使用
			System.out.println("认证时未登录");
			return null;
		}
		fillUserRealProperties(request, user);
		userService.updateRealName(user);
		downloadImage(request, file, user);
		sendMessage(UserConstant.CERTIFY, user.getId(), UserConstant.ADMIN_ID);
		return "submitCertify";
	}

	// 发送消息--即消息持久化
	private void sendMessage(String content, Long senderID, Long receiverId) {
		User sender = userService.getUserById(senderID);
		if (sender == null) {
			return;
		}
		if (content == UserConstant.CERTIFY) {

			content = sender.getUsername() + "申请实名认证";
		}
		MessageCenter message = new MessageCenter();
		message.setReceiver(receiverId);
		message.setSender(senderID);
		message.setStatus(MessageStatusEnum.UNREAD.getKey());
		message.setContent(content);
		messageCenterService.addMessage(message);

	}

	// 下载图片
	private void downloadImage(HttpServletRequest request, MultipartFile file,
			User user) {
		// 上传路径
		String dir = request.getSession().getServletContext()
				.getRealPath("/certifyImage");
		String filename = user.getUsername() + ".jpg";
		// System.out.println(dir + "   " + filename);
		File targetFile = new File(dir, filename);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 填充用户实名属性
	private void fillUserRealProperties(HttpServletRequest request, User user)
			throws UnsupportedEncodingException {
		String realName = request.getParameter("realName");
		String college = request.getParameter("college");
		// System.out.println("姓名" + realName);
		user.setStuId(request.getParameter("stuId"));
		user.setRealName(realName);
		user.setCollege(college);
	}

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		password = MD5.GetMD5Code(password);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("error");
		if (!request.getParameter("verifycode").equalsIgnoreCase(
				(String) request.getSession().getAttribute("randcode"))) {
			mav.addObject("errors", "验证码错误");
		} else {
			User user = userService.findByUsername(username);
			if (user != null) {
				String realPwd = user.getPassword();
				if (realPwd.equals(password)) {
					request.getSession().setAttribute("currentUser", user);
					mav.setViewName("loginsuccess");
				} else {
					mav.addObject("errors", "密码错误");
				}
			} else {
				mav.addObject("errors", "用户名错误");
			}
		}
		return mav;
	}

	@RequestMapping("/index")
	public ModelAndView toIndex(HttpServletRequest request,
			HttpServletResponse response) {
		Integer curPage = 1;
		Integer rowPerPage = 10;
		PageList pageList = new PageList("Goods", curPage, rowPerPage);
		List<Goods> allGoods = goodsService.getGoodsByPage(pageList);
		ModelAndView mav = new ModelAndView();
		getCategoryInfo(mav);
		mav.addObject("pageList", pageList);
		mav.addObject("allGoods", allGoods);
		mav.setViewName("index");
		return mav;
	}

	private void getCategoryInfo(ModelAndView mav) {
		Map<Category, ArrayList<Category>> categoriesMap = new HashMap<Category, ArrayList<Category>>();
		List<Category> largeCategories = categoryService.getLargeCategory();
		for (Category large : largeCategories) {
			ArrayList<Category> smallCategories = (ArrayList<Category>) categoryService
					.getSubCategory(large.getId());
			categoriesMap.put(large, smallCategories);
		}

		mav.addObject("largeCategories", largeCategories);
		mav.addObject("categoriesMap", categoriesMap);
	}

	private String readRequest(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader bufi = request.getReader();
			String line = null;
			while ((line = bufi.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
